#include "StdAfx.h"
#include "CxxImage.h"
#include "xImage.h"
#pragma comment(lib,"cximage.lib")
class CxxImage_imp
{
	CxImage m_img;
public:
	bool load( const TCHAR*path )
	{
		CString ss=path;
		ss.MakeLower();
		if(ss.Find(_T(".png"))>0)
		{
			return m_img.Load(path,CXIMAGE_FORMAT_PNG);
		}
		else if(ss.Find(_T(".jpg"))>0)
		{
			return m_img.Load(path,CXIMAGE_FORMAT_JPG);
		}
		else
		{
			return m_img.Load(path,0);
		}
		return false;
	}
	CSize getSize()const
	{
		return CSize(m_img.GetWidth(),m_img.GetHeight());
	}
	bool resample( __out ImageBuffer&buf,__in int cx,__in int cy,__out bool&bAlpha,__in bool bgra_order )
	{
		bool rt=m_img.Resample(cx,cy,0);
		ASSERT(rt);
		bAlpha = m_img.AlphaIsValid();
		if (bAlpha)
		{
			BYTE*buf1 = new BYTE[cx*cy * 4];
			if (bgra_order)
			{
				int k = 0;
				for (int y = 0; y < cy; ++y)
				{
					for (int x = 0; x < cx; ++x)
					{
						RGBQUAD cc = m_img.GetPixelColor(x, y);
						buf1[k] = cc.rgbBlue;
						buf1[k + 1] = cc.rgbGreen;
						buf1[k + 2] = cc.rgbRed;
						buf1[k + 3] = m_img.AlphaGet(x, y);
						k += 4;
					}
				}
			}
			else
			{
				int k = 0;
				for (int y = 0; y < cy; ++y)
				{
					for (int x = 0; x < cx; ++x)
					{
						RGBQUAD cc = m_img.GetPixelColor(x, y);
						buf1[k] = cc.rgbRed;
						buf1[k + 1] = cc.rgbGreen;
						buf1[k + 2] = cc.rgbBlue;
						buf1[k + 3] = m_img.AlphaGet(x, y);
						k += 4;
					}
				}
			}
			buf.m_pBuf = buf1;
			buf.m_bAutoDelete = TRUE;
		}
		else
		{
			BYTE*buf1 = new BYTE[cx*cy * 3];
			if (bgra_order)
			{
				int k = 0;
				for (int y = 0; y < cy; ++y)
				{
					for (int x = 0; x < cx; ++x)
					{
						RGBQUAD cc = m_img.GetPixelColor(x, y);
						buf1[k] = cc.rgbBlue;
						buf1[k + 1] = cc.rgbGreen;
						buf1[k + 2] = cc.rgbRed;
						k += 3;
					}
				}
			}
			else
			{
				int k = 0;
				for (int y = 0; y < cy; ++y)
				{
					for (int x = 0; x < cx; ++x)
					{
						RGBQUAD cc = m_img.GetPixelColor(x, y);
						buf1[k] = cc.rgbRed;
						buf1[k + 1] = cc.rgbGreen;
						buf1[k + 2] = cc.rgbBlue;
						k += 3;
					}
				}
			}
			buf.m_pBuf = buf1;
			buf.m_bAutoDelete = TRUE;
		}
		return rt;
	}
};
CxxImage::CxxImage(void)
{
	imp=new CxxImage_imp;
}


CxxImage::~CxxImage(void)
{
	delete imp;
}

bool CxxImage::load( const TCHAR*path )
{
	return imp->load(path);
}

CSize CxxImage::getSize() const
{
	return imp->getSize();
}

bool CxxImage::resample( __out ImageBuffer&buf,__in int cx,__in int cy,__out bool&bAlpha,__in bool bgra_order )
{
	return imp->resample(buf,cx,cy,bAlpha,bgra_order);
}

ImageBuffer::ImageBuffer()
{
	m_pBuf=NULL;
	m_bAutoDelete=TRUE;
}

ImageBuffer::~ImageBuffer()
{
	if(m_pBuf && m_bAutoDelete)
	{
		delete m_pBuf;
	}
}
